
package cn.sylinx.hbatis.ext.ifblock;

import java.util.Stack;

public class IfEndMatcherImpl implements IfEndMatcher {

	private Stack<String> stackIfend = new Stack<String>();
	private StringBuilder sbIfend = new StringBuilder();
	private char keyword = '#';

	@Override
	public String findMatchIfEnd(String partStatement) {

		stackIfend.clear();
		sbIfend.setLength(0);

		int len = partStatement.length();
		boolean meetKeyWord = false;
		String node = null;

		for (int i = 0; i < len; ++i) {

			char c = partStatement.charAt(i);
			if (keyword == c) {
				meetKeyWord = true;
				sbIfend.append(c);
				continue;
			}

			if (meetKeyWord) {
				sbIfend.append(c);
				node = sbIfend.toString();

				if (node.startsWith(Tags.VAR_PREFIX) || node.equals(Tags.KW_ELSIF) || node.equals(Tags.KW_ELSE)
						|| node.equals(Tags.KW_FUNC)) {
					// 遇到的是非#IF 和 #END
					sbIfend.setLength(0);
					meetKeyWord = false;

				} else if (node.equals(Tags.KW_IF)) {
					// 匹配到IF，需要进栈
					stackIfend.push(sbIfend.toString());

					sbIfend.setLength(0);
					meetKeyWord = false;

				} else if (node.equals(Tags.KW_END)) {
					// 匹配到END，需要出栈

					stackIfend.pop();

					if (stackIfend.empty()) {
						//
						return partStatement.substring(0, i + 1);

					} else {
						sbIfend.setLength(0);
						meetKeyWord = false;
					}

				}
			}
		}

		return null;
	}
}
